package zz.extjs.impl;

import java.util.Random;

import javax.servlet.http.HttpSession;

import zz.extjs.dao.Validate_code;

public class Validate_codeImpl implements Validate_code {

	private final int TYPE_NUMBER = 0;
	private final int TYPE_LETTER = 1;
	private final int TYPE_MULTIPLE = 2;

	private String getValidateCode(int size, int type) {
		StringBuffer validate_code = new StringBuffer();
		for (int i = 0; i < size; i++) {
			validate_code.append(getOneChar(type));
		}
		return validate_code.toString();
	}

	private String getOneChar(int type) {
		Random random = new Random();
		String result = null;
		switch (type) {
		case TYPE_NUMBER:
			result = String.valueOf(random.nextInt(10));
			break;
		case TYPE_LETTER:
			result = String.valueOf((char) (random.nextInt(26) + 65));
			break;
		case TYPE_MULTIPLE:
			if (random.nextBoolean()) {
				result = String.valueOf(random.nextInt(10));
			} else {
				result = String.valueOf((char) (random.nextInt(26) + 65));
			}
			break;
		default:
			result = null;
			break;
		}
		if (result == null)
			throw new NullPointerException("获取验证码出错");
		return result;
	}

	public String makeValidate_code(int size, int type, HttpSession session)
			throws Exception {
		// 用于产生验证码的字符串，并保存入session
		String result = null;
		result = getValidateCode(size, type);
		session.setAttribute("validate_code", result);
		return result;
	}

	public String makeMD5Operator(int size, int type, HttpSession session)
			throws Exception {
		// 用于产生md5随机数算子的字符串，并保存入session
		String result = null;
		result = getValidateCode(size, type);
		session.setAttribute("md5_oper", result);
		return result;
	}
}